package com.smartfast4j.manager.modules.sys.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.smartfast4j.common.annotation.NotEmpty;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.component.cache.annotation.CacheClear;
import com.smartfast4j.common.config.Cachekey;
import com.smartfast4j.manager.common.bean.CnAreaVo;
import com.smartfast4j.manager.common.bean.JsTree;
import com.smartfast4j.manager.common.bean.ZtreeAreaVo;
import com.smartfast4j.manager.common.controller.ManagerBaseController;
import com.smartfast4j.manager.modules.sys.service.SysCnAreaService;
import com.smartfast4j.pojo.sys.SysCnArea;
import com.smartfast4j.pojo.sys.SysCnAreaExample;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
* SysCnAreaController
*  由代码生成器生成
*/
@RestController
@RequestMapping("/sysCnArea")
public class SysCnAreaController extends ManagerBaseController {

    @Autowired
    private SysCnAreaService sysCnAreaService;

    /**
     * 分页查询行政区域
     * @param offset 从第几条开始取
     * @param limit 每次取多少条
     * @param name 资源名称
     * @return
     */
    @RequestMapping(value = "/list",name = "查询行政区域")
    public R list(Integer offset, Integer limit, String name, Long id){
        if (offset != null && limit != null) {
            //分页查询
            PageHelper.offsetPage(offset, limit);
        }
        SysCnAreaExample areaExample = new SysCnAreaExample();
        SysCnAreaExample.Criteria criteria = areaExample.createCriteria();
        if(StringUtils.isNotEmpty(name)){
            criteria.andNameLike("%"+name+"%");
        }
        if(id != null){
            criteria.andIdEqualTo(id);
        }
        List<SysCnArea> areaList = sysCnAreaService.selectByExample(areaExample);
        List<CnAreaVo> areaVoList = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(areaList)){
            Set<Long> parentIds = new HashSet<>();
            areaList.forEach(area -> parentIds.add(area.getParentId()));
            //查找区域的父区域
            areaExample = new SysCnAreaExample();
            areaExample.createCriteria().andIdIn(new ArrayList<>(parentIds));
            List<SysCnArea> parentAreaList = sysCnAreaService.selectByExample(areaExample);
            if(CollectionUtils.isNotEmpty(parentAreaList)){
                Map<Long,String> parentAreaMap = new HashMap<>();
                for(SysCnArea area:parentAreaList){
                    parentAreaMap.put(area.getId(),area.getName());
                }

                for(SysCnArea area:areaList){
                    CnAreaVo cnAreaVo = new CnAreaVo();
                    try {
                        //相同属性复制
                        BeanUtils.copyProperties(cnAreaVo,area);
                        //根据父ID获取父名称
                        cnAreaVo.setParentName(parentAreaMap.getOrDefault(cnAreaVo.getParentId(),""));
                        areaVoList.add(cnAreaVo);
                    } catch (Exception e) {
                        logger.error(e.getMessage(),e);
                    }
                }
            }
        }
        //分页信息
        PageInfo<SysCnArea> pageInfo = new PageInfo(areaList);
        Map<String,Object> dataMap = new HashMap<>();
        dataMap.put("total",pageInfo.getTotal());
        dataMap.put("rows", areaVoList);//需要显示的数据，将组织好的Vo数据进行展示
        //服务端分页，返回的结果必须包含total、rows两个参数。漏写或错写都会导致表格无法显示数据。
        return R.ok(dataMap);
    }

    /**
     * 根据区域ID获取区域信息以及子区域信息
     * @param id
     * @return
     */
    @RequestMapping(value = "/getAreaTreeById",name = "根据区域ID获取区域信息以及子区域信息")
    @NotEmpty("id")
    public R getAreaTreeById(Long id) {
        return R.ok(sysCnAreaService.getAreaTreeById(id));
    }

    /**
     * 加载中国行政区域树形结构
     * @param id
     * @return
     */
    @NotEmpty("id")
    @RequestMapping(value = "/loadAreaJsTree",name = "加载中国行政区域树形结构")
    public List<JsTree> loadAreaJsTree(String id){
        return sysCnAreaService.loadAreaJsTree(id);
    }

    /**
     * 加载中国行政区域树形结构
     * @param id
     * @return
     */
    @RequestMapping(value = "/loadAreaZtree",name = "加载中国行政区域树形结构")
    public List<ZtreeAreaVo> loadAreaZtree(String id){
        return sysCnAreaService.loadAreaZtree(id);
    }

    /**
     * 新增
     *
     */
    @RequestMapping("/add")
    public R add(SysCnArea sysCnArea) {
         sysCnAreaService.insertSelective(sysCnArea);
         return R.ok();
    }

    /**
     * 修改
     *
     */
    @CacheClear(key = "'" + Cachekey.Sys.AREA+ "' + #sysCnArea.id") //更新后清除缓存
    @RequestMapping("/update")
    public R update(SysCnArea sysCnArea) {
        sysCnAreaService.updateByPrimaryKeySelective(sysCnArea);
        return R.ok();
    }

    /**
     * 删除
     *
     */
    @RequestMapping("/delete")
    public R delete(Long id) {
        sysCnAreaService.deleteByPrimaryKey(id);
        return R.ok();
    }

     /**
     * 分页查询
     *
     */
    @RequestMapping("/pageList")
    public R pageList(@RequestParam(defaultValue = "1")int pageNum, @RequestParam(defaultValue = "10")int pageSize){
        SysCnAreaExample example = new SysCnAreaExample();
        //分页查询
        example.setLimitStart((pageNum-1) * pageSize);//从第几条开始取（索引从0开始）
        example.setLimitEnd(pageSize);//取多少条
        List<SysCnArea> dataList = sysCnAreaService.selectByExample(example);
        return R.ok(dataList);
    }
}
